import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/global/im/xmm_im_manager.dart';
import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/global/xmm_app_const.dart';
import 'package:bigegg/utils/xmm_event_bus.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import '../../../../../common/get/controller/xmm_base_controller.dart';
import '../../../../../data/repository/xmm_remote_repository.dart';
import '../../../../../entity/im/xmm_im_talk.dart';

class XmmConversationController extends XmmBaseGetxController {
  final repository = XmmRemoteRepository();

  final talkList = <XmmImTalk>[].obs;

  @override
  void onReady() {
    super.onReady();
    callback(arg) => getConversationList();
    XmmEventBus.instance.on(XmmAppConst.eventReceivedMessageKey, callback);
    XmmEventBus.instance.on(XmmAppConst.eventSendMessageKey, callback);
    XmmEventBus.instance.on(XmmAppConst.eventRemoveConversationKey, callback);
    XmmEventBus.instance.on(XmmAppConst.eventClearUnreadCountKey, callback);
    XmmEventBus.instance.on(XmmAppConst.eventBlockStatusUpdateKey, callback);
  }

  @override
  void onClose() {
    XmmEventBus.instance.off(XmmAppConst.eventReceivedMessageKey);
    XmmEventBus.instance.off(XmmAppConst.eventSendMessageKey);
    XmmEventBus.instance.off(XmmAppConst.eventRemoveConversationKey);
    XmmEventBus.instance.off(XmmAppConst.eventClearUnreadCountKey);
    XmmEventBus.instance.off(XmmAppConst.eventBlockStatusUpdateKey);
    super.onClose();
  }

  void deleteConversation(String userId) {
    XmmImManager.instance.removeConversation(userId);
  }

  void getConversationList({int startTime = 0}) {
    var conversationTypes = <RCIMIWConversationType>[
      RCIMIWConversationType.private
    ];
    IRCIMIWGetConversationsCallback? callback = IRCIMIWGetConversationsCallback(
      onSuccess: (List<RCIMIWConversation>? list) async {
        if (list?.isNotEmpty == true) {
          var conversationList = <XmmImTalk>[];
          for (var element in list!) {
            var user = XmmAccountManager.instance.findWallUser(element.targetId ?? "");
            if (user.userId == null) {
              user = await repository.getUserInfo(element.targetId ?? "");
              XmmAccountManager.instance.addWallUser(user);
            }
            if (user.isBlack != true) {
              conversationList.add(XmmImTalk(element, user));
            }
          }
          talkList.value = conversationList;
          talkList.refresh();
        } else {
          talkList.clear();
          talkList.refresh();
        }
      },
      onError: (int? code) {
        XmmXLogcat.d("getConversations result $code");
      },
    );
    XmmImManager.instance.engine?.getConversations(
      conversationTypes,
      null,
      startTime,
      50,
      callback: callback,
    );
  }
}
